﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;

namespace CalemShop
{
    public partial class FrmMain : Form
    {
        public FrmStock frmStock = null;
        public FrmSale frmSale = null;
        public FrmInvoice frmInvoice = null;
        public FrmReportIncome frmIncome = null;
        public FrmCheckStock frmCheckStock = null;
        public FrmBarcodePrinter frmPrintBarcode = null;
        public FrmInputStock frmInputStock = null;
        public FrmCustomer frmCustomer = null;
        private Thread reportThread;
        private static bool hasSendReport = false;
        private static bool hasBackup = false;
        private bool isReportStop = false;
        public static RegistryKey calemRegistry = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);
        public RegistryKey reportRegistry = null;

        public FrmMain()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            if (calemRegistry != null)
            {
                reportRegistry = calemRegistry.CreateSubKey(@"software\Calem\report\daily", RegistryKeyPermissionCheck.ReadWriteSubTree);
            }
            reportThread = new Thread(new ThreadStart(doDailyReport));
        }

        private void mnChecking_Click(object sender, EventArgs e)
        {
            string text = "Kết nối CSDL thành công";
            if (DBConnection.testConnection() == false)
            {
                text = "Kết nối CSLD thất bại";
            }

            doShowMessage("Thông báo", text);
        }

        private void mnLogin_Click(object sender, EventArgs e)
        {
            doShowLogin();
        }



        private FrmLogin doShowLogin()
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.MdiParent = this;
            frmLogin.StartPosition = FormStartPosition.CenterScreen;
            frmLogin.Show();
            return frmLogin;
        }

        public void doShowMessage(string title, string message)
        {
            FrmMsgBox msg = new FrmMsgBox();
            msg.Text = title;
            msg.txtMessage.Text = message;
            msg.MdiParent = this;
            msg.StartPosition = FormStartPosition.CenterScreen;
            msg.WindowState = FormWindowState.Normal;
            msg.Show();
        }


        private void mnSale_Click(object sender, EventArgs e)
        {
            if (frmSale == null)
            {
                frmSale = new FrmSale();
                frmSale.MdiParent = this;
                frmSale.StartPosition = FormStartPosition.CenterScreen;
                frmSale.WindowState = FormWindowState.Maximized;
                frmSale.Show();
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            reportThread.Start();
            lbReport.Text = "Daily report is active";
        }

        private void mnStock_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            if (frmLogin.ShowDialog(this) == DialogResult.OK && frmLogin.loginOk == true && frmLogin.isAdmin)
            {
                foreach (Form f in this.MdiChildren)
                {
                    f.Close();
                }

                if (frmStock == null)
                {
                    frmStock = new FrmStock();
                    frmStock.MdiParent = this;
                    frmStock.StartPosition = FormStartPosition.CenterScreen;
                    frmStock.WindowState = FormWindowState.Maximized;
                    frmStock.Show();
                }
                else
                {
                    frmStock.Show();
                }
            }
            else
            {
                doShowMessage("Thông báo", "Chức năng này cần đăng nhập mới sử dụng được");
            }

        }

        private void mnHoaDon_Click(object sender, EventArgs e)
        {
            if (frmInvoice == null)
            {
                frmInvoice = new FrmInvoice();
                frmInvoice.MdiParent = this;
                frmInvoice.StartPosition = FormStartPosition.CenterScreen;
                frmInvoice.WindowState = FormWindowState.Maximized;
                frmInvoice.Show();
            }
            else
            {
                frmInvoice.Show();
            }
        }

        private void mnDoanhThu_Click(object sender, EventArgs e)
        {
            if (frmIncome == null)
            {
                frmIncome = new FrmReportIncome();
                frmIncome.MdiParent = this;
                frmIncome.Show();
                frmIncome.StartPosition = FormStartPosition.CenterScreen;
                frmIncome.WindowState = FormWindowState.Maximized;

            }
            else
            {
                frmIncome.Show();
            }
        }

        private void doDailyReport()
        {
            while (isReportStop == false)
            {
                try
                {
                    DateTime now = DateTime.Now;
                    if (now.Hour == 18)
                    {
                        if (now.Minute >= 10 && now.Minute <= 45)
                        //if (now.Minute >= 00 && now.Minute <= 59)
                        {

                            if (!hasSendReport)
                            {
                                string sub = string.Format("[CALEMSHOP] Daily Report {0}", now.ToString("dd-MM-yyyy HH:mm"));
                                StringBuilder builder = new StringBuilder();
                                builder.Append(@"<h3>Ngày :" + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss") + "</h1>");
                                builder.Append(@"<hr>");
                                builder.Append(System.Environment.NewLine);
                                builder.Append(@"+ Tổng tiền thu được : <b>");
                                builder.Append(Database.totalIncomeToday().ToString("#,0")).Append(" VNĐ </b>");
                                builder.Append(@"<br/>");
                                builder.Append(@"+ Số khách trả hàng :");
                                builder.Append(Database.countInvoiceReturnToday()).Append(" lần");
                                builder.Append(@"<br/>");
                                builder.Append(@"+ Tổng số hóa đơn bán :");
                                builder.Append(Database.countInvoice(DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")));
                                builder.Append(@"<br/>");

                                DataTable db = Database.reportSellers(DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd"));
                                if (db != null)
                                {
                                    foreach (DataRow r in db.Rows)
                                    {
                                        string dname = (string)r["seller"];
                                        double value = double.Parse(r["sellerIncome"].ToString());
                                        builder.Append(string.Format("<b>+ {0} </b> bán được : {1}</b>", dname, value.ToString("#,0")));
                                        builder.Append(@"<br/>");
                                    }

                                }

                                if (reportRegistry != null)
                                {
                                    string reportKeyValue = now.ToString("dd-MM-yyyy hh");
                                    string value = (string)reportRegistry.GetValue("report", string.Empty);
                                    if (string.IsNullOrEmpty(value) == false && string.Compare(value, reportKeyValue, true) == 0)
                                    {
                                        hasSendReport = true;
                                    }
                                }

                                if (hasSendReport == false)
                                {
                                    hasSendReport = GMail.sendMail(new string[] { "calemshop@gmail.com", "trucmai2211@yahoo.com", "vinhan21@yahoo.com.vn" }, sub, builder.ToString());
                                    if (hasSendReport)
                                    {
                                        string reportKeyValue = now.ToString("dd-MM-yyyy hh");
                                        if (reportRegistry != null)
                                        {
                                            reportRegistry.SetValue("report", reportKeyValue);
                                        }
                                    }
                                }

                                if (hasSendReport)
                                {
                                    lbReport.Text = "Send report success";
                                }
                            }

                            //==================
                            if (!hasBackup)
                            {
                                hasBackup = BackupUtil.doBackupData();
                                if (hasBackup)
                                {
                                    lbReport.Text = "Backup data success";
                                }
                            }
                        }
                        else
                        {
                            lbReport.Text = "Daily report is active";
                        }
                    }
                    else
                    {
                        hasSendReport = false;
                        hasBackup = false;
                        lbReport.Text = "Daily report is active";
                    }

                    Thread.Sleep(5000);
                }
                catch (ThreadInterruptedException)
                {
                    return;
                }
                catch (Exception ex)
                {
                    lbReport.Text = ex.Message;
                }
            }

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                isReportStop = true;
                reportThread.Interrupt();
                reportThread.Join();
            }
            catch (Exception) { }
        }

        private void mnCheckStock_Click(object sender, EventArgs e)
        {
            if (frmCheckStock == null)
            {
                frmCheckStock = new FrmCheckStock();
                frmCheckStock.MdiParent = this;
                frmCheckStock.StartPosition = FormStartPosition.CenterScreen;
                frmCheckStock.WindowState = FormWindowState.Maximized;
                frmCheckStock.Show();
            }
            else
            {
                frmCheckStock.Show();
            }
        }

        private void mnPrintBarcode_Click(object sender, EventArgs e)
        {
            if (frmPrintBarcode == null)
            {
                frmPrintBarcode = new FrmBarcodePrinter();
                frmPrintBarcode.MdiParent = this;
                frmPrintBarcode.StartPosition = FormStartPosition.CenterScreen;
                frmPrintBarcode.WindowState = FormWindowState.Maximized;
                frmPrintBarcode.Show();
            }
            else
            {
                frmPrintBarcode.Show();
            }
        }

        private void mnInputStock_Click(object sender, EventArgs e)
        {
            if (frmInputStock == null)
            {
                frmInputStock = new FrmInputStock();
                frmInputStock.MdiParent = this;
                frmInputStock.StartPosition = FormStartPosition.CenterScreen;
                frmInputStock.WindowState = FormWindowState.Maximized;
                frmInputStock.Show();
            }
            else
            {
                frmInputStock.Show();
            }
        }

        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            /*if (e.KeyCode == Keys.A)
            {
                e.Handled = true;
                MessageBox.Show("Handle");
                
                return;
            }*/

        }

        private void mnCustomer_Click(object sender, EventArgs e)
        {
            if (frmCustomer == null)
            {
                frmCustomer = new FrmCustomer();
                frmCustomer.MdiParent = this;
                frmCustomer.StartPosition = FormStartPosition.CenterScreen;
                frmCustomer.WindowState = FormWindowState.Maximized;
                frmCustomer.Show();
            }
            else
            {
                frmCustomer.Show();
            }
        }

    }
}
